//
//  WLMHomeTableViewController.swift
//  WeiBo
//
//  Created by Eric on 2017-01-04.
//  Copyright © 2017 Eric. All rights reserved.
//

import UIKit
import SVProgressHUD

private let homeCellId = "WLMStatusCellId"
private let retweetedStatusCellId = "WLMRetweetedStatusCellId"

class WLMHomeTableViewController: WLMBaseTableViewController {

    lazy var homeViewModel: WLMHomeViewModel = WLMHomeViewModel()
    lazy var homeRefreshContol: WLMRefreshControl = WLMRefreshControl()
    internal lazy var indicatorView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        return indicator
    }()
    
    private lazy var tipLabel: UILabel = {
        let label = UILabel(text: "", fonSize: 16, textColor: UIColor.white)
        label.backgroundColor = UIColor.orange
        label.textAlignment = .center
        label.isHidden = true
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogin {
            
            visitorView.visitorViewInfo(name: "visitordiscover_feed_image_smallicon", title: "关注一些人到这里看看有什么惊喜", isHome: true)
            return
        }
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", titleName: nil, target: self, action: #selector(goAfter))
        
        //设置tableView
        
        setupTableView()
        loadData()
        
    }
    func loadData() {
        
        //加载数据
        self.homeViewModel.loadData(isPullUp: indicatorView.isAnimating) { (success,count) in
            if !success {
                SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                return
            }
            if !self.indicatorView.isAnimating {
                self.showMessage(count: count)
            }
            self.indicatorView.stopAnimating()
            self.homeRefreshContol.endRefreshing()
            self.tableView.reloadData()
        }
        
    }
    //提示更新几条
    private func showMessage(count: Int) {
        if tipLabel.isHidden == false {
            return
        }
        let tipText = count == 0 ? "没有新微博" : "更新了\(count)条微博"
        tipLabel.text = tipText
        self.tipLabel.isHidden = false
        
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.frame.origin.y = navBarHeight
        }, completion:{ (_) -> () in
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = y
            }, completion: { (_) -> () in
                self.tipLabel.isHidden = true
            })
        })
    }
    
    
    private func setupTableView() {
        let cellNib = UINib(nibName: "WLMStatusCell", bundle: nil)
        self.tableView.register(cellNib, forCellReuseIdentifier: "WLMStatusCellId")
        
        let retweetedNib = UINib(nibName: "WLMRetweetedStatusCell", bundle: nil)
        self.tableView.register(retweetedNib, forCellReuseIdentifier: "WLMRetweetedStatusCellId")
        
//        self.tableView.estimatedRowHeight = 100
        tableView.separatorStyle = .none
        
        self.tableView.tableFooterView = indicatorView
        
        homeRefreshContol.addTarget(self, action: #selector(loadData), for: .valueChanged)
        self.view.addSubview(homeRefreshContol)
        
        
//        let refreshControl = WLMRefreshControl()
//        self.view.addSubview(refreshControl)
//        
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        tipLabel.frame.origin.y = navBarHeight - 35
//
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
    }
    
    @objc private func goAfter() {
        
        let viewController = WLMTestViewController()
        
        navigationController?.pushViewController(viewController, animated: true)
    }

}


extension WLMHomeTableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.homeViewModel.viewModelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.homeViewModel.viewModelArray[indexPath.row]
        let cellId = getCellId(viewModel: model)
        let cell = getCell(cellId: cellId)
        cell.viewModel = model
        return cell
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = self.homeViewModel.viewModelArray[indexPath.row]
        let name = getCellId(viewModel: model)
        let cell = getCell(cellId: name)
        
        cell.viewModel = model
        
        cell.layoutIfNeeded()
        
        return cell.toolBox.frame.maxY
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indicatorView.isAnimating == false && indexPath.row == homeViewModel.viewModelArray.count - 2 {
            print("^^^ 静默加载")
            indicatorView.startAnimating()
            loadData()
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath)
        cell?.selectionStyle = .none
    }
    
    private func getCell(cellId: String) -> WLMStatusCell {
        return cellId == homeCellId ? UINib(nibName: "WLMStatusCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! WLMStatusCell : UINib(nibName: "WLMRetweetedStatusCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! WLMStatusCell
    }
    
    private func getCellId(viewModel: WLMHomeCellModel) -> String {
        return viewModel.status?.retweeted_status == nil ? homeCellId : retweetedStatusCellId
    }
}
